<template>
  <div>
    <div class="w-full h-12" style="margin-top: 57px">
      <div class="py-2 content">
        <div class="float-left w-40">
          <img :src="getSettingbyKey('home_logo')" style="width: 189.69px; height: 50px; margin-bottom: 13px" />
        </div>

        <div class="float-right" style="width: 500px">
          <el-row>
            <el-col :span="3" class="text-center pt-6"> <el-link href="/" target="_blank">首页</el-link></el-col>
            <el-col :span="4" class="text-center pt-6">
              <el-link href="/fmjg" target="_blank">价格与服务</el-link></el-col
            >
            <el-col :span="3" class="text-center pt-6"> <el-link href="/mb" target="_blank">模板库</el-link></el-col>
            <el-col :span="3" class="text-center pt-6"> <el-link href="#" target="_blank">帮助</el-link></el-col>
            <!-- <el-col :span="3" class="text-center pt-6">
              <el-link href="https://element-plus.org" target="_blank">管理后台</el-link></el-col
            > -->
            <el-col :span="8" class="text-center pt-6"> <login /> </el-col>
          </el-row>
        </div>
      </div>
    </div>

    <div style="clear: both"></div>

    <div v-if="showmenu" class="w-full" style="min-width: 1200px; color: #000; background-color: #ffe60f">
      <div class="content">
        <el-menu :default-active="activeIndex" mode="horizontal" style="width: 1200px" @select="handleSelect2">
          <el-menu-item index="1">静态码</el-menu-item>

          <el-menu-item index="2">音视频</el-menu-item>
          <el-menu-item index="3">图片</el-menu-item>
          <el-menu-item index="4">网址</el-menu-item>
          <el-menu-item index="5">名片</el-menu-item>
          <el-menu-item index="6">文件</el-menu-item>
          <el-menu-item index="7">表单</el-menu-item>
          <!-- <el-menu-item index="8">电子画册</el-menu-item> -->
          <el-menu-item index="9">批量生成</el-menu-item>
          <el-menu-item index="10">二维码解码</el-menu-item>

          <el-menu-item index="11" style="width: 235px">
            <template #title>
              <el-icon>
                <Edit />
              </el-icon>
              <el-link href="/v3" target="_blank"> <span>高级编辑器</span></el-link>
            </template>
          </el-menu-item>
        </el-menu>
        <input type="file" ref="fileInput" accept="image/*" style="display: none" />
        <!-- <div class="absolute right-0 top-0 pt-4">
          <el-text>
            <el-icon>
              <Edit />
            </el-icon>

            <router-link to="/editor?mode=v1">高级编辑器</router-link>

          </el-text>
        </div> -->
      </div>
    </div>
    <el-dialog v-model="dialogVisible" width="500" @open="wxloginopen" @close="stopTimer">
      <div class="p-16" v-loading="loading">
        <img v-if="loginEQ" :src="loginEQ" class="w-48 h-48" style="margin: 0 auto" />
      </div>
      <!-- <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="dialogVisible = false"> Confirm </el-button>
        </div>
      </template> -->
    </el-dialog>
    <el-popover ref="popoverRef" :visible="popoverShow" width="200px" trigger="click" virtual-triggering persistent>
      <div>
        <el-menu default-active="1" class="el-menu-vertical-demo" @select="handleSelect">
          <el-menu-item index="1" style="width: 100%">
            <el-icon>
              <Avatar />
            </el-icon>
            <span>个人信息</span>
          </el-menu-item>
          <el-menu-item index="2" style="width: 100%">
            <el-icon>
              <Grid />
            </el-icon>
            <span>管理后台</span>
          </el-menu-item>
          <!-- <el-menu-item index="3"  style="width: 100%">
            <el-icon>
              <PieChart />
            </el-icon>
            <span>扫码统计</span>
          </el-menu-item> -->

          <el-menu-item index="4" style="width: 100%">
            <el-icon>
              <SwitchButton />
            </el-icon>
            <span>安全退出</span>
          </el-menu-item>
        </el-menu>
      </div>
    </el-popover>
    <el-dialog title="解析结果" v-model="v">
      {{ result }}
    </el-dialog>
  </div>
</template>

<script setup>
import axios from 'axios';
import { ref } from 'vue';
import { fileput } from '@/utils/ali-oss';
import moment from 'moment';
import { getSettingbyKey } from '@/utils/index.js';
import { loginpclog_list, tempalte_list, saveQrcode } from '@/api/index.js';
import SnowflakeId from 'snowflake-id';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';

import EventBus from '@/utils/event-bus.js';
const props = defineProps({
  index: Number,
  showmenu: {
    type: Boolean, // S 必须大写
    default: true,
  },
});

import login from '@/views/components/index/login.vue';
const router = useRouter();
import jsqr from 'jsqr';
const snowflake = new SnowflakeId();
const dialogVisible = ref(false);
const activeIndex = ref(props.index);
const loginEQ = ref('');
const popoverRef = ref();
const popoverShow = ref(false);
const userinfo = ref({});
//localStorage.setItem('userinfo', '{"createBy":null,"createTime":null,"updateBy":null,"updateTime":null,"remark":null,"id":1,"uWxOpenid":"oMeua61EGEYZcJebCHPWpaWFaYNI","uPhone":"18624024313","uNikename":"羽然香","ueId":null,"uAvatar":"https://ecodeuserstore.oss-cn-beijing.aliyuncs.com/UserAvatar/YfidCMsBwn.jpeg","uShareratio":null,"createdTime":"2024-04-19 05:17:00","updatedTime":null,"uState":0,"pDistribuUserid":null,"uLevel":null,"isDistritution":null,"uVipLevel":null,"limitImgtxtone":6291456,"limitImgtxtsum":100,"limitAudiovideoone":62914560,"limitAudiovideosum":100,"vipName":"vip1","user_companyName":null}')
userinfo.value = JSON.parse(localStorage.getItem('userinfo'));
console.log('userinfo.value', userinfo.value);
const loading = ref(true);
const intervalId = ref(null);
const textarea = ref('');
const qrCode = ref('https://www.hlcode.cn/_nuxt/img/qr-default-2.5129466.png');
const showToast = inject('$showToast');
const v = ref(false);
async function wxloginopen() {
  let id = snowflake.generate();
  const instance = axios.create({
    baseURL: '/weixin',
    // 指定请求超时的毫秒数
    timeout: 1000,
    // 表示跨域请求时是否需要使用凭证
    withCredentials: false,
  });
  await instance({
    method: 'get',
    url: '/cgi-bin/token?grant_type=client_credential&appid=wxfb02cc61a6ef3971&secret=fabd1914b14d949a04b1041883a4ee3b',
  }).then(async (res) => {
    await instance({
      method: 'post',
      url: `/wxa/getwxacodeunlimit?access_token=${res.data.access_token}`,
      data: {
        scene: id,

        page: 'pages/userinfo/pclogin', // 这里按照需求设置值和参数
      },
      responseType: 'arraybuffer',
    }).then((res2) => {
      console.log('res2', res2);
      const arrayBuffer = res2.data;
      return new Promise((resolve, reject) => {
        // 创建一个Blob对象
        const blob = new Blob([arrayBuffer], { type: 'application/octet-stream' });

        // 创建一个FileReader对象
        const reader = new FileReader();

        // 定义FileReader的onload事件处理函数
        reader.onload = function (event) {
          // 将ArrayBuffer转换为Base64编码的字符串
          const base64String = event.target.result;
          resolve(base64String);
        };

        // 定义FileReader的onerror事件处理函数
        reader.onerror = function (error) {
          reject(error);
        };

        // 将Blob转换为Data URL并触发onload事件
        reader.readAsDataURL(blob);
      }).then((base64String) => {
        console.log('base64String', base64String);
        loginEQ.value = base64String;
        loading.value = false;
        console.log('loginEQ', loginEQ.value);

        // 设置3分钟等于180000毫秒
        const threeMinutes = 3 * 60 * 1000;

        intervalId.value = setInterval(function () {
          loginjg(id);
        }, 1000); // 每1000毫秒（即每秒）调用一次 loginjg 方法

        // 使用 setTimeout 来停止 setInterval
        setTimeout(function () {
          clearInterval(intervalId);
        }, threeMinutes);
      });
    });
  });
}
function stopTimer() {
  if (intervalId.value) {
    clearInterval(intervalId.value);
    console.log('计时器已停止');
  }
}

function loginjg(code) {
  loginpclog_list({ pcCode: code }).then((res) => {
    if (res.data.code === 200 && res.data.data.userinfo) {
      userinfo.value = res.data.data.userinfo;
      localStorage.setItem('userinfo', JSON.stringify(res.data.data.userinfo));
      localStorage.setItem('vipinfo', JSON.stringify(res.data.data.vipinfo));
      dialogVisible.value = false;
      stopTimer();
    }
  });
}
const handleSelect = (key, keyPath) => {
  console.log(key, keyPath);
  switch (key) {
    case '1':
      break;
    case '2':
      router.push('/admin');
      break;
    case '3':
      break;
    case '4':
      loginout();
      break;
  }
};
const fileInput = ref(null);
const handleSelect2 = (key, keyPath) => {
  console.log(key, keyPath);
  switch (key) {
    case '1':
      router.push('/');
      break;
    case '2':
      router.push('/av');
      break;
    case '3':
      router.push('/img');
      break;
    case '4':
      router.push('/url');
      break;
    case '5':
      router.push('/card');
      break;
    case '6':
      router.push('/file');
      break;
    case '7':
      router.push('/form');
      break;
    case '9':
      ElMessage.success('功能开发中...');
      break;
    case '10':
      fileInput.value.click();
      break;
  }
};
function loginout() {
  //删除 localStorage 中的 userinfo
  localStorage.removeItem('userinfo');
  userinfo.value = null;
  popoverShow.value = false;
}
const list3 = ref([]);
function tempalte_list_fun() {
  tempalte_list({ tcId: -1 }).then((res3) => {
    console.log('res3', res3);
    list3.value = res3.data.data.listdata;
  });
}
const list4 = ref([]);
function tradecategory_list_fun() {
  tempalte_list({ tpId: -1 }).then((res3) => {
    list4.value = res3.data.data.listdata;
  });
}
tempalte_list_fun();
tradecategory_list_fun();
const result = ref('');
const handleFileUpload = () => {
  const file = fileInput.value.files[0];
  console.log('file:', file);
  if (!file) {
    return;
  }

  // 创建FileReader对象来读取文件内容
  const reader = new FileReader();

  // 当文件读取完成时触发的函数
  reader.onload = (event) => {
    const img = new Image();
    img.onload = () => {
      // 使用jsqr库解析二维码图像
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      canvas.width = img.width;
      canvas.height = img.height;
      ctx.drawImage(img, 0, 0, img.width, img.height);
      const imageData = ctx.getImageData(0, 0, img.width, img.height);
      const code = jsqr(imageData.data, imageData.width, imageData.height);
      console.log('code:', code);

      if (code) {
        result.value = ` ${code.data}`;
        console.log('result.value:', result.value);
        v.value = true;
      } else {
        result.value = '未识别到二维码内容';
      }
    };
    img.src = event.target.result;
  };

  // 读取文件作为数据URL
  reader.readAsDataURL(file);
};
onMounted(() => {
  const inputElement = fileInput.value;
  if (inputElement) {
    inputElement.addEventListener('change', handleFileUpload);
  }
});
</script>
<style>
.content {
  width: 1200px;
  margin: 0 auto;
}

.el-menu--horizontal {
  height: 46px !important;
}
</style>
<style scoped>
.inputDeep >>> .el-input__inner {
  border: 0;
  box-shadow: 0 0 0 0;
}
</style>
<style scoped lang="less">
.pass_input {
  // el-input__inner是el-input的input类名
  & /deep/ .el-input__inner {
    border: none;
  }
}

.el-menu {
  border-right: solid 1px var(--el-menu-border-color);
  list-style: none;
  position: relative;
  margin: 0;
  padding-left: 0;
  background-color: transparent !important;
  box-sizing: border-box;
}

.el-menu-item {
  width: 100px;
}

.el-menu--horizontal .el-menu-item:not(.is-disabled):hover,
.el-menu--horizontal .el-menu-item:not(.is-disabled):focus {
  outline: none;
  color: #fff !important;
  background-color: #333333 !important;
}

.el-menu--horizontal.el-menu {
  border-bottom: solid 0px var(--el-menu-border-color) !important;
}

.el-menu--horizontal > .el-menu-item.is-active {
  border-bottom: 0px solid #f1c40f !important;
  background-color: #333333 !important;
  color: #fff !important;
  border-radius: 0px;
}

.el-menu--horizontal > .el-menu-item:hover {
  border-bottom: 0px solid #f1c40f !important;
  background-color: #333333 !important;
  color: #fff !important;
  border-radius: 0px;
}

.el-menu--horizontal > .el-menu-item:focus {
  border-bottom: 0px solid #f1c40f !important;
  background-color: #333333 !important;
  color: #fff !important;
  border-radius: 8px;
}

.el-menu--horizontal {
  display: flex;

  flex-wrap: nowrap;
  border-right: none;
  height: 46px !important;
}

.c {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  padding: 20px;
  min-width: 1200px;
}

.borderNone {
  :deep(.el-input__wrapper) {
    box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color)) inset;
    cursor: default;

    .el-input__inner {
      cursor: default !important;
      border: 0 !important;
    }
  }
}
</style>

